package com.zhxy.util.api.test.store;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

import org.junit.Assert;

import com.zhxy.util.UncaughtException;
import com.zhxy.util.api.store.FileMetadata;
import com.zhxy.util.api.store.FileStore;

public class FileStoreTestCase {
	
	private FileStore fileStore;

	public void setFileStore(FileStore fileStore) {
		this.fileStore = fileStore;
	}
	
	public void fulltest() {
		
		try {
			byte[] data = createTempData();
			String originName = "test.bin";
			Date now = new Date();
			
			String key = fileStore.store(new ByteArrayInputStream(data), originName);
			Assert.assertNotNull(key);
			
			FileMetadata meta = fileStore.getMetadata(key);
			Assert.assertNotNull(meta);
			
			Assert.assertEquals(meta.getKey(), key);
			Assert.assertEquals(meta.getOriginName(), originName);
			Assert.assertTrue(now.getTime() <= meta.getStoredDate().getTime());
			
			InputStream input = meta.getInputStream();
			Assert.assertNotNull(input);
			
			byte[] buf = new byte[data.length];
			input.read(buf);
			Assert.assertTrue(Arrays.equals(data, buf));
			
			fileStore.remove(key);
			
		} catch (IOException e) {
			throw new UncaughtException(e);
		}
	}
	
	/**
	 * 创建随机的数据
	 * @return
	 */
	private byte[] createTempData() {
		
		Random random = new Random(System.currentTimeMillis());

		byte[] buf = new byte[1024];
		random.nextBytes(buf);
		return buf;
	}
}
